<?php

class Logger {

	/**
	 * 错误级别
	 */
	const LOGGER_LEVEL_TRACE = 1;
	const LOGGER_LEVEL_DEBUG = 2;
	const LOGGER_LEVEL_WARNING = 3;
	const LOGGER_LEVEL_ERROR = 4;
	const LOGGER_LEVEL_FATAL = 5;
	const LOGGER_LEVEL_LOG = 6;

	const OUTPUT = ROOT_PATH . '/log';

	/**
	 * crlf
	 * 换行符
	 *
	 * @var string
	 */
	public static $crlf = PHP_EOL;

	/**
	 * debug
	 *
	 * @param mixed $message
	 * @access public
	 * @return void
	 */
	public static function debug($message, $noReport = true) {
		return Logger::log($message, self::LOGGER_LEVEL_DEBUG, $noReport);
	}

	/**
	 * warning
	 *
	 * @param mixed $message
	 * @access public
	 * @return void
	 */
	public static function warning($message) {
		return Logger::log($message, self::LOGGER_LEVEL_WARNING);
	}

	/**
	 * trace
	 *
	 * @param mixed $message
	 * @access public
	 * @return void
	 */
	public static function trace($message, $noReport = false) {
		return Logger::log($message, self::LOGGER_LEVEL_TRACE, $noReport);
	}

	/**
	 * fatal
	 *
	 * @param mixed $message
	 * @access public
	 * @return void
	 */
	public static function fatal($message) {
		return Logger::log($message, self::LOGGER_LEVEL_FATAL);
	}

	/**
	 * error
	 *
	 * @param string $message
	 * @access public
	 * @return void
	 */
	public static function error($message) {
		return Logger::log($message, self::LOGGER_LEVEL_ERROR);
	}

	/**
	 * log
	 *
	 * @param mixed $message
	 * @param mixed $level
	 * @access public
	 * @return string
	 */
	public static function log($message, $level = self::LOGGER_LEVEL_LOG) {

		Shell::mkDir(self::OUTPUT);
		if ($message instanceof Exception) {
			$message = sprintf('[%s:%d] %d:%s', str_replace(ROOT_PATH, '', $message->getFile()), $message->getLine(), $message->getCode(), $message->getMessage());
		}

		$backtrace = debug_backtrace();
		while (true) {
			if ($backtrace[1]['class'] != 'Logger') {
				break;
			}
			array_shift($backtrace);
		}

		$traceinfo = array(
			'file' => str_replace(ROOT_PATH, '', $backtrace[0]['file']),
			'line' => $backtrace[0]['line'],
		);

		switch ($level) {
			case self::LOGGER_LEVEL_TRACE:
				$myLevel = 'TRACE';
				break;
			case self::LOGGER_LEVEL_DEBUG:
				$myLevel = 'DEBUG';
				break;
			case self::LOGGER_LEVEL_WARNING:
				$myLevel = 'WARNING';
				break;
			case self::LOGGER_LEVEL_ERROR:
				$myLevel = 'ERROR';
				break;
			case self::LOGGER_LEVEL_FATAL:
				$myLevel = 'FATAL';
				break;
			case self::LOGGER_LEVEL_LOG:
				$myLevel = 'LOG';
				break;
			default:
				$myLevel = 'N/A';
		}

		$out = sprintf("[%s] [%s:%d] [%s] %s" . self::$crlf,
			date('Y-m-d H:i:s'), @$traceinfo['file'], @$traceinfo['line'], $myLevel, $message);
		$file = 'api_' . PLUGIN_ID;
		$file = str_replace('.', '_', $file);
		$outfile = self::OUTPUT . "/$file";
		$outfile .= '.' . date('Y-m-d') . '.log';
		if ($fd = @fopen($outfile, 'a+')) {
			fwrite($fd, $out);
			fclose($fd);
		} else {
			error_log("Logger: Cannot open file ($outfile)");
		}

		return $outfile;
	}

}
